package com.fram.service.admin.botany.impl;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.fram.bean.admin.botany.request.BotanyBasicMessageRequest;
import com.fram.bean.admin.botany.response.BotanyBasicMessageResponse;
import com.fram.bean.admin.user.response.LoginResponse;
import com.fram.bean.sys.PageBean;
import com.fram.common.canstant.BotanyConstantMethod;
import com.fram.common.canstant.ErrCode;
import com.fram.common.exception.ProAffairException;
import com.fram.common.exception.ProRunTimeException;
import com.fram.common.util.date.DateUtils;
import com.fram.common.util.excel.ExcelUtils;
import com.fram.common.util.file.FileUtils;
import com.fram.entity.BotanyBasicMessage;
import com.fram.entity.BotanyCategory;
import com.fram.entity.BotanyDetailMessage;
import com.fram.entity.BotanyImages;
import com.fram.mapper.BotanyBasicMessageMapper;
import com.fram.mapper.BotanyCategoryMapper;
import com.fram.mapper.BotanyDetailMessageMapper;
import com.fram.mapper.BotanyImagesMapper;
import com.fram.mapper.UserMapper;
import com.fram.service.admin.botany.BotanyMessageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * @作者： 陳曉鬆 @时间： 2020年7月2日 - 下午3:59:31 @description：->
 */
@Service("botanyMessageService")
public class BotanyMessageServiceImpl implements BotanyMessageService {

	@Autowired
	private BotanyBasicMessageMapper botanyBasicMessageMapper;
	@Autowired
	private BotanyDetailMessageMapper botanyDetailMessageMapper;
	@Autowired
	private BotanyImagesMapper botanyImagesMapper;
	@Autowired
	private BotanyCategoryMapper botanyCategoryMapper;
	@Autowired
	private UserMapper userMapper;

	@Override
	@Transactional
	public void insertBotanyBasicMessage(BotanyBasicMessage request) throws ProAffairException {
		if (botanyBasicMessageMapper.insertSelective(request) == 0) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), ErrCode.FAIL.getReturnMsg());
		}
	}

	@Override
	@Transactional
	public void updateBotanyBasicMessage(BotanyBasicMessage request) throws ProAffairException {
		if (botanyBasicMessageMapper.updateByPrimaryKeySelective(request) == 0) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), ErrCode.FAIL.getReturnMsg());
		}
	}

	@Override
	public PageInfo<BotanyBasicMessageResponse> queryBasicMessage(PageBean<BotanyBasicMessageRequest> request) throws ProAffairException {
		PageHelper.startPage(request.getPageNum(), request.getPageSize());
		List<BotanyBasicMessageResponse> list = botanyBasicMessageMapper.queryBasicMessage(request.getParam());
		if (list == null || list.size() == 0) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return new PageInfo<>(list);
	}

	@Override
	@Transactional
	public Long insertBotanyDetailMessage(BotanyDetailMessage request) throws ProAffairException {
		if (botanyDetailMessageMapper.insertSelective(request) == 0 || request.getId() == null) {
			throw new ProRunTimeException(ErrCode.FAIL.getReturnCode(), ErrCode.FAIL.getReturnMsg());
		}
		return request.getId();
	}

	@Override
	@Transactional
	public List<String> uploadImage(Long basicId, Long detailId, List<MultipartFile> files) throws ProAffairException {
		if (files == null || files.size() == 0) {
			throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), "没有检测到文件");
		}
		MultipartFile file = null;
		for (int i = 0; i < files.size(); i++) {
			file = files.get(i);
			if (!file.isEmpty()) {
				try {
					// 获取图片的文件名
					String fileName = file.getOriginalFilename();
					if (!"png,jpg".contains(// 获取图片的扩展名
							fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase())) {
						throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), fileName + ":只支持jpg、png的文件上传");
					}
					if (file.getSize() > BotanyConstantMethod.maxSize) {
						throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), fileName + ":最大上传文件：" + BotanyConstantMethod.maxSize / 1024 / 1024 + "M");
					}
				} catch (Exception e) {
					e.printStackTrace();
					throw new ProRunTimeException(ErrCode.ERR_PARAMETER.getReturnCode(), "参数解析有误");
				}
			}
		}
		// 先设置一个数组来装file路径
		List<String> imgs = new ArrayList<String>();
		// 设置图片路径
		String uploadPath = BotanyConstantMethod.getPath(basicId, detailId);
		for (int i = 0; i < files.size(); i++) {
			file = files.get(i);
			if (!file.isEmpty()) {
				try {
					byte[] bytes = file.getBytes();
					// 获取图片的文件名
					String fileName = file.getOriginalFilename();
					// 新的图片文件名 = 获取时间戳+"."图片扩展名
					String newFileName = BotanyConstantMethod.getFileName(fileName, basicId, detailId);
					// 图片路径
					Path path = Paths.get(uploadPath + newFileName);
					// 如果没有files文件夹，则创建
					if (!Files.isWritable(path)) {
						Files.createDirectories(Paths.get(uploadPath));
					}
					// 文件写入指定路径
					Files.write(path, bytes);

					BotanyImages images = new BotanyImages();
					images.setBasicId(basicId);
					images.setDetailId(detailId);
					images.setUrl(newFileName);
					if (botanyImagesMapper.insertSelective(images) == 0) {
						Files.delete(path);
					}
					imgs.add(newFileName);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return imgs;
	}

	@Override
	public String zipDownPath(Long basicId) throws ProAffairException {
		BotanyBasicMessage basicMessage = botanyBasicMessageMapper.selectByPrimaryKey(basicId);
		if (basicMessage == null) {
			throw new ProRunTimeException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		LoginResponse user = null;
		if (basicMessage.getAdminUserId() != null) {
			user = userMapper.selectByUserIdForAdmin(basicMessage.getAdminUserId());
		}
		BotanyCategory category = botanyCategoryMapper.selectByPrimaryKey(basicMessage.getCategoryId());
		if (category == null) {
			category = new BotanyCategory();
		}
		List<Map<String, String>> data = new ArrayList<Map<String, String>>();
		Map<String, String> title = new HashMap<String, String>();
		title.put("name_0", "基地名称");
		title.put("name_1", "植物名称");
		title.put("name_2", "植物类型");
		title.put("name_3", "省");
		title.put("name_4", "市");
		title.put("name_5", "区、县");
		title.put("name_6", "分数");
		title.put("name_7", "创建时间");
		title.put("name_8", "简单介绍");
		if (user != null) {
			title.put("name_9", "用户昵称");
		}
		data.add(title);
		Map<String, String> map = new HashMap<String, String>();
		map.put("name_0", basicMessage.getNameOfBase());
		map.put("name_1", basicMessage.getName());
		map.put("name_2", category.getCategoryName());
		map.put("name_3", basicMessage.getProvinceName());
		map.put("name_4", basicMessage.getCityName());
		map.put("name_5", basicMessage.getAreaName());
		map.put("name_6", basicMessage.getBoranyFraction() + "");
		map.put("name_7", DateUtils.DF_SEPARATE.get().format(basicMessage.getCreateTime()));
		map.put("name_8", basicMessage.getIntroduce());
		if (user != null) {
			map.put("name_9", user.getName());
		}
		data.add(map);
		map = new HashMap<String, String>();
		map.put("name_0", "-------------");
		map.put("name_1", "-------------");
		map.put("name_2", "-------------");
		map.put("name_3", "-------------");
		map.put("name_4", "--分割线----");
		map.put("name_5", "-------------");
		map.put("name_6", "-------------");
		map.put("name_7", "-------------");
		map.put("name_8", "-------------");
		if (user != null) {
			map.put("name_9", "-------------");
		}
		data.add(map);
		// 详细信息
		List<BotanyDetailMessage> detailMessage = botanyDetailMessageMapper.botanyDetailMessageList(basicMessage.getId());
		if (detailMessage != null && detailMessage.size() != 0) {
			title = new HashMap<String, String>();
			title.put("name_0", "录入时间");
			title.put("name_1", "植物数据");
			title.put("name_2", "开花结果数据");
			title.put("name_3", "播种数据");
			title.put("name_4", "植物状态");
			title.put("name_5", "生长天数");
			title.put("name_6", "采摘数量");
			title.put("name_7", "是否异常");
			title.put("name_8", "异常症状");
			title.put("name_9", "异常原因");
			title.put("name_10", "解决方案");
			title.put("name_11", "备注信息");
			title.put("name_12", "上传用户");
			title.put("name_13", "图片文件路径");
			data.add(title);

			for (BotanyDetailMessage b : detailMessage) {
				map = new HashMap<String, String>();
				map.put("name_0", DateUtils.DF_SEPARATE.get().format(b.getCreateTime()));
				map.put("name_1", b.getBotanyData());
				map.put("name_2", b.getBlossomFruitData());
				map.put("name_3", b.getSowData());
				map.put("name_4", b.getBotanyStatus());
				map.put("name_5", b.getGrowthDays() + "");
				map.put("name_6", b.getPickNumber() + b.getPickCountingUnit());
				map.put("name_7", b.getIsAbnormal() == 1 ? "正常" : "异常");
				map.put("name_8", b.getAbnormalSymptom());
				map.put("name_9", b.getAbnormalReason());
				map.put("name_10", b.getSolution());
				map.put("name_11", b.getRemark());
				map.put("name_12", b.getUserName());
				map.put("name_13", "/" + b.getId());
				data.add(map);
			}
		}
		String path = BotanyConstantMethod.getPath(basicMessage.getId(), null);
		String excelPath = path + "植物信息成长数据.xlsx";
		ExcelUtils.writeExcel(data, excelPath);
		Long time = System.currentTimeMillis();
		String zipPath = BotanyConstantMethod.getBasePath() + "botany_data_" + time + ".zip";
		FileUtils.toZip(path, BotanyConstantMethod.getBasePath(), "botany_data_" + time, true);
		FileUtils.deleteFile(excelPath);
		return zipPath;
	}

}
